package com.upload.jms.login;


import com.upload.bean.yCoin.LoginRequestBean;
import com.upload.bean.yCoin.LoginResponseBean;
import com.upload.service.LoginService;
import com.upload.util.JSONUtil;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Created by huangying on 2017/3/28.
 */
//@Component
public class LoginServer {

    private final static String QUEUE_NAME = "login.fileUpload.queue";

    private final static Logger LOG = LoggerFactory.getLogger(LoginServer.class);


    @JmsListener(destination = QUEUE_NAME)
    public void handler(Message message) throws JMSException, InterruptedException {

        if (message instanceof ActiveMQTextMessage) {
            LOG.info("server receive.");
            ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
            LoginRequestBean requestBean = JSONUtil.toBean(textMessage.getText(), LoginRequestBean.class);
            LoginResponseBean responseBean = loginService.loginHandler(requestBean);
            LOG.info("server send.");
            System.out.println(textMessage.getJMSReplyTo());
            System.out.println(responseBean);

            Thread.sleep(1000);
//            Destination responseDest = textMessage.getJMSReplyTo();
//            long expiration = textMessage.getExpiration();
//            System.out.println("expiration = " + expiration);
//            System.out.println(responseDest);

            //如果超时，DestinationDoesNotExistException
            jmsTemplate.convertAndSend(textMessage.getJMSReplyTo(), responseBean.toString());

//            jmsTemplate.execute(textMessage.getJMSReplyTo(), new ProducerCallback<Object>() {
//                public Object doInJms(Session session, MessageProducer producer) throws JMSException {
//                    return null;
//                }
//            });

        }
    }

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private LoginService loginService;
}
